package com.tanyoujie.cart.interceptor;

import com.tanyoujie.cart.to.UserInfoTo;
import com.tyj.common.constant.AuthServerConstant;
import com.tyj.common.constant.CartConstant;
import com.tyj.common.vo.MemberRespVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal=new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        MemberRespVo memberEntity = (MemberRespVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        UserInfoTo userInfoTo=new UserInfoTo();
        //判断用户是否是登录状态
        if (memberEntity!=null){
            //处于登录状态
            userInfoTo.setUserId(memberEntity.getId());
            Cookie[] cookies=request.getCookies();
            if (cookies!=null){
                for (Cookie cookie : cookies) {
                    if (CartConstant.TEMP_USER_COOKIE_NAME.equals(cookie.getName())){
                        userInfoTo.setUserKey(cookie.getValue());
                        userInfoTo.setTempUser(true);
                    }
                }
            }
        }else {
            //不处于登录状态 获得当前的零时Cookie令牌
            Cookie[] cookies=request.getCookies();
            if (cookies!=null){
                for (Cookie cookie : cookies) {
                    if (CartConstant.TEMP_USER_COOKIE_NAME.equals(cookie.getName())){
                        userInfoTo.setUserKey(cookie.getValue());
                        userInfoTo.setTempUser(true);
                    }
                }
            }
        }

        //3 如果浏览器没有user-key，我们通过uuid生成user-key
        if (StringUtils.isEmpty(userInfoTo.getUserKey())){
            String uuid= UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }
        threadLocal.set(userInfoTo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        //若页面没有找到该user-key 需要给页面返回该cookie
        if (!userInfoTo.getTempUser()) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }

}
